package com.stars.system.reim.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.stars.system.reim.domain.ReimDailyRecord;
import com.stars.system.reim.domain.ReimDailyRecordVO;
import com.stars.system.reim.service.IReimDailyRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 报销记录（个人）Controller
 * 
 * @author shuaibizhe
 * @date 2022-11-14
 */
@RestController
@RequestMapping("/reim/daily/record")
public class ReimDailyRecordController extends BaseController
{
    @Autowired
    private IReimDailyRecordService dailyRecordService;

    /**
     * 查询报销记录（个人）列表
     */
    @PreAuthorize("@ss.hasPermi('daily:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request , ReimDailyRecord reimRecord)
    {
        startPage();
        // 报销管理员 查看全部数据
        if (!getLoginUser().getUser().isReimAdmin()) {
            reimRecord.setReimSpender(SecurityUtils.getUserId());
        }
        return getDataTable(dailyRecordService.selectReimDailyRecordList(reimRecord));
    }

    /**
     * 查询报销记录（个人）列表
     */
    @PreAuthorize("@ss.hasPermi('daily:record:list')")
    @GetMapping("/listGroup")
    public TableDataInfo listGroup(HttpServletRequest request , ReimDailyRecord reimRecord)
    {
        startPage();
        // 报销管理员 查看全部数据
        if (!getLoginUser().getUser().isReimAdmin()) {
            reimRecord.setReimSpender(SecurityUtils.getUserId());
        }
        List<ReimDailyRecord> records = dailyRecordService.selectReimDailyRecordList(reimRecord);
        if (CollectionUtils.isEmpty(records)) {
            return getDataTable(new ArrayList<>());
        }
        int total = records.size();
        List<ReimDailyRecordVO> recordVOS =dailyRecordService.buildRecordsByMonthGroup(records);
        return getDataTable(recordVOS, total);
    }

    /**
     * 导出报销记录（个人）列表
     */
//    @PreAuthorize("@ss.hasPermi('daily:record:export')")
//    @Log(title = "报销记录（个人）", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, ReimDailyRecord reimRecord)
//    {
//        List<ReimDailyRecord> list = dailyRecordService.selectReimDailyRecordList(reimRecord);
//        ExcelUtil<ReimDailyRecord> util = new ExcelUtil<ReimDailyRecord>(ReimDailyRecord.class);
//        util.exportExcel(response, list, "报销记录（个人）数据");
//    }

    /**
     * 获取报销记录（个人）详细信息
     */
    @PreAuthorize("@ss.hasPermi('daily:record:query')")
    @GetMapping(value = "/{reimId}")
    public AjaxResult getInfo(@PathVariable("reimId") String reimId)
    {
        return AjaxResult.success(dailyRecordService.selectReimDailyRecordByReimId(reimId));
    }

    /**
     * 新增报销记录（个人）
     */
//    @PreAuthorize("@ss.hasPermi('daily:record:add')")
    @Log(title = "报销记录（个人）", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ReimDailyRecord reimRecord)
    {
        return toAjax(dailyRecordService.insertReimDailyRecord(reimRecord));
    }

    /**
     * 修改报销记录（个人）
     */
    @PreAuthorize("@ss.hasPermi('daily:record:edit')")
    @Log(title = "报销记录（个人）", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ReimDailyRecord reimRecord)
    {
        return toAjax(dailyRecordService.updateReimDailyRecord(reimRecord));
    }

    /**
     * 删除报销记录（个人）
     */
    @PreAuthorize("@ss.hasPermi('daily:record:remove')")
    @Log(title = "报销记录（个人）", businessType = BusinessType.DELETE)
	@DeleteMapping("/{reimIds}")
    public AjaxResult remove(@PathVariable String[] reimIds)
    {
        return toAjax(dailyRecordService.deleteReimDailyRecordByReimIds(reimIds));
    }

    /**
     * 统计前确认数据
     */
    @PreAuthorize("@ss.hasPermi('daily:record:stat')")
    @GetMapping(value = {"/confirm/{reimIds}", "/confirm/"})
    public Map confirm(@PathVariable(required = false) String[] reimIds)
    {
        if (reimIds == null || reimIds.length == 0) {
            return Map.of("flag",true);
        }
        int cycle = 40;
        return Map.of("flag",reimIds.length == 0 ? true : dailyRecordService.confirmDailyBeforeStat(reimIds, cycle),
                "msg","存在距今" + cycle + "天以上的报销记录，是否依然进行统计？",
                "reimIds",reimIds);
    }

    /**
     * 统计数据
     */
    @PreAuthorize("@ss.hasPermi('daily:record:stat')")
    @GetMapping(value = {"/stat/{reimIds}", "/stat/"})
    public TableDataInfo stat(@PathVariable(required = false) String[] reimIds)
    {
        if (reimIds == null || reimIds.length == 0) {
            return getDataTable(new ArrayList<>());
        }
        return getDataTable(dailyRecordService.statReimDailyRecord(reimIds));
    }

    /**
     * 生成支付记录word文档
     */
    @PreAuthorize("@ss.hasPermi('daily:record:stat')")
    @GetMapping(value = {"/imgs/{reimIds}", "/imgs/"})
    public void imgs(@PathVariable(required = false) String[] reimIds, HttpServletResponse response, HttpServletRequest request) throws Exception {
        dailyRecordService.exportReimDailyRecordImgs(reimIds, response, request);
    }

    /**
     * 生成报销封面excel文档
     */
    @PreAuthorize("@ss.hasPermi('daily:record:stat')")
    @GetMapping(value = {"/cover/{reimIds}", "/cover/"})
    public void cover(@PathVariable(required = false) String[] reimIds, HttpServletResponse response, HttpServletRequest request) throws Exception {
        dailyRecordService.exportReimDailyRecordCover(reimIds, response, request);
    }

    /**
     * 将数据标记为报销完成
     */
    @PreAuthorize("@ss.hasPermi('daily:record:stat')")
    @GetMapping(value = {"/complete/{reimIds}", "/complete/"})
    public AjaxResult complete(@PathVariable(required = false) String[] reimIds)
    {
        return toAjax(dailyRecordService.completeReimDailyRecord(reimIds));
    }

    protected TableDataInfo getDataTable(List<?> list, int total)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);
        return rspData;
    }
}
